"""
日志配置模块
"""
import sys
from functools import wraps
from pathlib import Path
from loguru import logger
from typing import Optional

from .config import settings


class LoggingConfig:
    """日志配置类"""
    
    def __init__(self):
        self.log_dir = Path(settings.log_dir)
        self.log_dir.mkdir(parents=True, exist_ok=True)
        
        # 移除默认处理器
        logger.remove()
        
        # 配置日志格式
        self.log_format = (
            "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
            "<level>{level: <8}</level> | "
            "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
            "<level>{message}</level>"
        )
        
        # 添加控制台处理器
        self._add_console_handler()
        
        # 添加文件处理器
        self._add_file_handlers()
    
    def _add_console_handler(self):
        """添加控制台日志处理器"""
        logger.add(
            sys.stdout,
            format=self.log_format,
            level=settings.log_level,
            colorize=True,
            backtrace=True,
            diagnose=True,
        )
    
    def _add_file_handlers(self):
        """添加文件日志处理器"""
        
        # 日常日志文件
        logger.add(
            self.log_dir / "daily" / "app_{time:YYYY-MM-DD}.log",
            format=self.log_format,
            level=settings.log_level,
            rotation="00:00",
            retention="30 days",
            compression="zip",
            encoding="utf-8",
            backtrace=True,
            diagnose=True,
        )
        
        # 错误日志文件
        logger.add(
            self.log_dir / "errors" / "error_{time:YYYY-MM-DD}.log",
            format=self.log_format,
            level="ERROR",
            rotation="00:00",
            retention="90 days",
            compression="zip",
            encoding="utf-8",
            backtrace=True,
            diagnose=True,
        )
        
        # 性能日志文件
        logger.add(
            self.log_dir / "performance" / "performance_{time:YYYY-MM-DD}.log",
            format="{time:YYYY-MM-DD HH:mm:ss} | {message}",
            level="INFO",
            rotation="00:00",
            retention="30 days",
            compression="zip",
            encoding="utf-8",
            filter=lambda record: "performance" in record["extra"],
        )
    
    def get_logger(self, name: Optional[str] = None):
        """获取日志记录器"""
        if name:
            return logger.bind(name=name)
        return logger


# 初始化日志配置
logging_config = LoggingConfig()


def get_logger(name: Optional[str] = None):
    """获取日志记录器"""
    return logging_config.get_logger(name)


# 性能日志装饰器
def log_performance(func_name: str = None):
    """性能日志装饰器"""
    def decorator(func):
        name = func_name or f"{func.__module__}.{func.__name__}"
        
        def wrapper(*args, **kwargs):
            import time
            start_time = time.time()
            
            try:
                result = func(*args, **kwargs)
                execution_time = time.time() - start_time
                
                logger.bind(performance=True).info(
                    f"Performance: {name} executed in {execution_time:.3f}s"
                )
                
                return result
            except Exception as e:
                execution_time = time.time() - start_time
                
                logger.bind(performance=True).error(
                    f"Performance: {name} failed after {execution_time:.3f}s - {str(e)}"
                )
                raise
        
        return wrapper
    return decorator


# 数据库操作日志装饰器
def log_db_operation(operation: str):
    """数据库操作日志装饰器"""
    def decorator(func):
        def wrapper(*args, **kwargs):
            logger.bind(db_operation=True).info(
                f"Database operation started: {operation}"
            )
            
            try:
                result = func(*args, **kwargs)
                logger.bind(db_operation=True).info(
                    f"Database operation completed: {operation}"
                )
                return result
            except Exception as e:
                logger.bind(db_operation=True).error(
                    f"Database operation failed: {operation} - {str(e)}"
                )
                raise
        
        return wrapper
    return decorator


# API请求日志装饰器
def log_api_request(endpoint: str):
    """API请求日志装饰器"""
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            # logger.bind(api_request=True).info( f"API request started: {endpoint}")
            try:
                result = await func(*args, **kwargs)
                logger.bind(api_request=True).info(f"API request completed: {endpoint}")
                return result
            except Exception as e:
                logger.bind(api_request=True).error(f"API request failed: {endpoint} - {str(e)}")
                raise
        
        return wrapper
    return decorator


# 全局日志记录器
app_logger = get_logger("petition_app")
db_logger = get_logger("petition_db")
api_logger = get_logger("petition_api")
ai_logger = get_logger("petition_ai")